import dayjs from 'dayjs'
import { computed, onUnmounted, ref } from 'vue'

// 封装倒计时函数
export const useCountDown = () => {
  let timer = null
  // 1.响应式的数据
  const time = ref(0)
  // 格式化时间为 xx分xx秒
  const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
  // 2.开启倒计时的函数
  const start = (currentTime) => {
    // 核心逻辑：每隔1s减一
    time.value = currentTime
    if (timer) clearInterval(timer)
    timer = setInterval(() => {
      if (time.value > 0) {
        time.value--
      } else {
        clearInterval(timer)
        time.value = 0 // 倒计时结束设为 0，显示固定值
      }
    }, 1000)
  }
  // 组件销毁时停止倒计时
  onUnmounted(() => {
    timer && clearInterval(timer)
  })
  return { formatTime, start }
}
